package app.server.project.core.httpauth;

import app.server.project.core.constants.CfgDef;
import app.server.project.core.constants.Def;
import app.server.project.core.exception.SysError;
import app.server.project.core.token.TokenCache;
import app.server.project.core.util.AssertUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenCache tokenCache;


    @Value("${" + CfgDef.chkToken + ":" + false + "}")
    private boolean chkToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!chkToken)return true;
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (Objects.isNull(handlerMethod.getMethodAnnotation(UnAuth.class))){
                var userId=request.getHeader(Def.UserId);
                if (StrUtil.isBlank(userId)){
                    log.info("header 没有带UserId");
                }
                AssertUtil.isTrue(StrUtil.isNotBlank(userId), SysError.UserId);
                var token=request.getHeader(Def.Token);
                if (StrUtil.isBlank(token)){
                    log.info("header 没有带token");
                }
                AssertUtil.isTrue(StrUtil.isNotBlank(token), SysError.Token);
                var cache=this.tokenCache.getToken(Long.parseLong(userId));
                log.info("缓存 token:{}",cache);
                log.info("userid:{}=====token:{}",userId,token);
                AssertUtil.isTrue(StrUtil.isNotBlank(cache), SysError.EmptyToken);
                AssertUtil.isTrue(token.equals(cache),SysError.ErrorToken);
            }
            return true;
        }
        return false;
    }
}
